/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Lenovo
 * Date: 2025-07-08
 * Time: 0:09
 */
//https://leetcode.cn/problems/balanced-binary-tree/submissions/642089622/
    //给定一个二叉树，判断它是否是 平衡二叉树
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
public class Test {
    public static boolean isBalanced(TreeNode root) {
        if(root==null){
            return true;
        }
        return fun(root)==-1?false:true;
    }
    public static int fun(TreeNode root){
        if(root==null){
            return 0;
        }
        int left=fun(root.left);
        if(left==-1){
            return -1;
        }
        int right=fun(root.right);
        if(right==-1){
            return -1;
        }
        if(Math.abs(left-right)>1){
            return -1;
        }
        return Math.max(left,right)+1;
    }

    public static void main(String[] args) {
        TreeNode A1=new TreeNode(1);
        TreeNode A2=new TreeNode(2);
        TreeNode A3=new TreeNode(3);
        TreeNode A4=new TreeNode(4);
        TreeNode A5=new TreeNode(5);
        TreeNode A6=new TreeNode(6);
        TreeNode A7=new TreeNode(7);
        A1.left=A2;A1.right=A3;
        A2.left=A4;A2.right=A5;
        A3.left=A6;A3.right=A7;
        System.out.println(isBalanced(A1));
    }
}
